# k-means 实例，sklearn
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs

np.random.seed(123)
X, y = make_blobs(centers=4, n_samples=1000)#生成4个随机簇
print('数据的维数:', X.shape)
print('数据的簇标签：', y)

plt.figure()
plt.scatter(X[:,0], X[:,1], c=y)
plt.title("Dataset with 4 clusters")
plt.xlabel("X")
plt.ylabel("Y")

k = 2  # 2， 3， 4， 5
kmeans = KMeans(n_clusters=k)
kmeans.fit(X)


label_pred = kmeans.labels_



# print(label_pred.shape)
centroids = kmeans.cluster_centers_
print('簇中心坐标：', centroids)
inertia = kmeans.inertia_

# 聚类评价指标
from sklearn.metrics import silhouette_score, calinski_harabasz_score,  davies_bouldin_score
print('聚类指标silhouette_score：', silhouette_score(X, label_pred))  #值越接近1，表示聚类效果越好。
print('聚类指标calinski_harabasz_score：', calinski_harabasz_score(X, label_pred))#值越大表示聚类效果越好。
print('聚类指标davies_bouldin_score：', davies_bouldin_score(X, label_pred)) #值越小表示聚类效果越好




# 绘图
plt.figure()
plt.scatter(X[:,0], X[:,1], c=label_pred)
plt.scatter(centroids[:, 0], centroids[:, 1], c='k', marker='s')

plt.show()